package com.example.ssss;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.ssss.data.entity.Threshold;
import com.example.ssss.data.entity.Wheel;
import com.example.ssss.data.util.JsonParse;
import com.example.ssss.data.MyMqttService;
import com.example.ssss.data.entity.MyMqttMessage;
import com.example.ssss.databinding.ActivityPretestBinding;
import com.example.ssss.request.PretestRequestViewModel;
import com.example.ssss.state.MyMqttServiceViewModel;
import com.example.ssss.state.PretestStateViewModel;

import java.util.HashMap;

public class PretestActivity extends AppCompatActivity {

    ActivityPretestBinding binding;
    PretestStateViewModel stateViewModel;
    PretestRequestViewModel requestViewModel;
    MyMqttServiceViewModel mqttViewModel;
    MyMqttService mqttService;
    MyMqttServiceConn myServiceConn;
    MyMqttService.LocalBinder binder = null;
    private Intent bindIntent = null;
    SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
    HashMap<Integer, Integer> soundPoolMap = new HashMap<Integer, Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //保持屏幕常量
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

//        setContentView(R.layout.activity_pretest);
        stateViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(PretestStateViewModel.class);
        requestViewModel = new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory()).get(PretestRequestViewModel.class);
        mqttViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MyMqttServiceViewModel.class);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_pretest);
        binding.setVm(stateViewModel);
        binding.setClick(new ClickClass());
        binding.setLifecycleOwner(this);

        stateViewModel.setHeadText(this.getString(R.string.testHeadBegin));
        stateViewModel.setTested(false);
        stateViewModel.setTempState(false);
        stateViewModel.setTempText(this.getString(R.string.tempTestBegin));
        stateViewModel.setAlcoholState(false);
        stateViewModel.setAlcoholText(this.getString(R.string.alcoholTestBegin));
        mqttService = new MyMqttService();
        bindIntent = new Intent(this,MyMqttService.class);
        myServiceConn = new MyMqttServiceConn();

        initSound();

        //turn on the wheel device
        mqttService.publish("ESP32_wheel_A0001_switch","{\"flag\":1}");
        mqttService.publish("ESP32_wear_W0001_on","1");

        //bind MyMqttService
        bindService(bindIntent,myServiceConn, Context.BIND_AUTO_CREATE);


//        MutableLiveData<String> serviceObserve = mqttViewModel.serviceObserve;
//        serviceObserve.observe(this, new Observer<String>() {
//            @Override
//            public void onChanged(String s) {
//                Log.d("mqtt","livedata change.");
//            }
//        });
    }

    //TODO 接收到体温与酒精数据后的操作
    public void afterReceived(MyMqttMessage msg){
        Wheel wheel = JsonParse.jsonToWheel(msg.getMessage());
        long millTime = wheel.millTime;
        double bodyTemp = wheel.bodyTemperature;
        int alcohol = wheel.alcohol;
        stateViewModel.setTested(true);
        if (bodyTemp < Threshold.TEMPERATURE && alcohol < Threshold.ALCOHOl){
            //体温和酒精通过检测
            Log.d("mqtt","体温和酒精通过检测");
            playSound(2,0);
            stateViewModel.setTempState(true);
            stateViewModel.setTempText(String.valueOf(bodyTemp)+"℃ 体温正常");
            stateViewModel.setAlcoholState(true);
            stateViewModel.setAlcoholText(this.getString(R.string.alcoholTestGood));
            stateViewModel.setHeadText("检测通过");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //要延时的程序
                    Intent intent=null;
                    intent=new Intent(getApplicationContext(),DrivingDetectionActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//为待启动的Activity指定FLAG_ACTIVITY_NEW_TASK标记位。
                    getApplicationContext().startActivity(intent);
                    finish();
                }
            },1000); //8000为毫秒单位
        }else{
            //未通过
            if(bodyTemp > Threshold.TEMPERATURE){
            //体温未通过检测
                Log.d("mqtt","体温未通过检测");
                playSound(3,0);
                stateViewModel.setTempState(false);
                stateViewModel.setTempText(String.valueOf(bodyTemp)+"℃ 体温过高");
                stateViewModel.setHeadText("检测未通过");
            }
            if (alcohol > Threshold.ALCOHOl){
            //酒精未通过检测
                Log.d("mqtt","酒精未通过检测");
                playSound(4,0);
                stateViewModel.setAlcoholState(false);
                stateViewModel.setAlcoholText(this.getString(R.string.alcoholTestBad));
                stateViewModel.setHeadText("检测未通过");
            }
            //弹窗
            AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("出发前检测未通过")
                    .setCancelable(false)
                    .setIcon(R.drawable.warning)
                    .setMessage("您目前的身体状况不适合继续驾驶，请更改您的出行计划！\n\n是否需要联系您的紧急联系人？")
                    .setPositiveButton("需要", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Toast.makeText(PretestActivity.this, "即将呼叫紧急联系人", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNeutralButton("返回", new DialogInterface.OnClickListener() {//添加取消
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    })
                    .create();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //要延时的程序
                    alertDialog.show();
                }
            },1000); //1000为毫秒单位
        }

    }

    class MyMqttServiceConn implements ServiceConnection{
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MyMqttService.LocalBinder) service;
            binder.getService().setWheelDataCallback(new MyMqttService.WheelCallback() {
                @Override
                public void wheelDataChanged(MyMqttMessage myMqttMessage) {
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("mqttMessage",myMqttMessage);
                    msg.setData(bundle);
                    //发送通知
                    handler.sendMessage(msg);
                }
            });
        }

        @SuppressLint("HandlerLeak")
        Handler handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                MyMqttMessage myMqttMessage = (MyMqttMessage)msg.getData().getSerializable("mqttMessage");
                afterReceived(myMqttMessage);
                String str_msg = myMqttMessage.getMessage();
                String str_topic = myMqttMessage.getTopic();
                Log.d("mqtt","handle message:\n"+str_msg);
            }
        };


        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder = null;
        }
    }

    public class ClickClass{
        public void returnAction(){
//            Intent mIntent = new Intent(PretestActivity.this, VideoDetectActivity.class);
//            startActivity(mIntent);
            mqttService.publish("switch_wear_on","1");
            MyMqttService mqttService = new MyMqttService();
            finish();
        }
    }

    private void initSound(){
        soundPoolMap.put(1, soundPool.load(this, R.raw.pretest, 1));
        soundPoolMap.put(2, soundPool.load(this, R.raw.pass, 2));
        soundPoolMap.put(3, soundPool.load(this, R.raw.body_temp_caution, 3));
        soundPoolMap.put(4, soundPool.load(this, R.raw.alcohol_caution, 4));

        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int i, int i2) {

                if(i==1) playSound(1,0);
            }
        });
    }
    private void playSound(int sound, int loop) {
        AudioManager mgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        soundPool.play(soundPoolMap.get(sound), 1, 1, 1, loop, 1f);
        //参数：1、Map中取值   2、左声道音量     3、右声道音量  4、优先级   5、重播次数   6、播放速度
    }

}